<template>
    <div class="container">
        <el-form
            ref="formRef"
            v-loading="formLoading"
            :model="formData"
            :rules="formRules"
            label-width="140px"
        >
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="总数量" prop="count">
                        <el-input-number
                            v-model="formData.count"
                            clearable
                            :controls="false"
                            class="!w-1/1"
                            placeholder="请输入总数量"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="原始平均值" prop="targetMean">
                        <el-input-number
                            v-model="formData.targetMean"
                            clearable
                            :controls="false"
                            class="!w-1/1"
                            :precision="2"
                            :step="0.1"
                            placeholder="请输入原始平均值"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="正负加减平均值" prop="targetStdDev">
                        <el-input-number
                            v-model="formData.targetStdDev"
                            clearable
                            :controls="false"
                            class="!w-1/1"
                            placeholder="请输入正负加减平均值"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="几位小数" prop="decimalPlaces">
                        <el-input-number
                            v-model="formData.decimalPlaces"
                            clearable
                            :controls="false"
                            class="!w-1/1"
                            placeholder="请输入几位小数"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="最大值" prop="maxValue">
                        <el-input-number
                            v-model="formData.maxValue"
                            clearable
                            :min="formData.targetMean"
                            :controls="false"
                            class="!w-1/1"
                            placeholder="请输入最大值"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6" v-if="!props.mode">
                    <el-button :disabled="formLoading" type="primary" @click="handle">生成</el-button>
                    <el-button @click="exportToExcel">导出为 Excel</el-button>
                </el-col>
            </el-row>
        </el-form>
        <div v-if="!props.mode">
            <el-table :data="tableData" height="80vh">
                <!-- 添加序号列 -->
                <el-table-column type="index" label="序号" width="200"></el-table-column>
                <el-table-column v-for="item in columnData" :key="item.prop" :label="item.label" :prop="item.prop"/>
            </el-table>
        </div>
    </div>
</template>


<script lang="ts" setup>
import {onMounted, onUnmounted, reactive, ref, watch} from "vue";
import {copyValue, generateRandomNumbers} from "@/views/Home/index";
import * as XLSX from 'xlsx';
import {saveAs} from 'file-saver';

const props = defineProps({
    modelValue: {
        type: Object,
        default: {}
    },
    // 组件模式
    mode: {
        type: Boolean,
        default: false
    }
})
onMounted(() => {
    if (!props.mode) {
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Enter' || event.keyCode === 13) {
                handle()
            }
        });
    }
})
const state = reactive({
    csvValue: ''
})

onUnmounted(() => {
    window.removeEventListener('keypress', handle);
})

const formRef = ref() // 表单 Ref
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
    count: undefined,
    targetMean: undefined,
    targetStdDev: undefined,
    maxValue: undefined,
    decimalPlaces: 0,
})
watch(
    formData.value,
    (n, o) => {
        emit('update:modelValue', o)
    },
    { deep: true }
)
const emit = defineEmits(['update:modelValue'])
const formRules = reactive({
    count: [{required: true, message: '不能为空', trigger: 'blur'}],
    targetMean: [{required: true, message: '不能为空', trigger: 'blur'}],
    targetStdDev: [{required: true, message: '不能为空', trigger: 'blur'}],
    // maxValue: [{required: true, message: '不能为空', trigger: 'blur'}],
})
const tableData = ref([]);

const columnData = ref([
    {prop: 'num', label: '数量'},
]);

const resetTableData = () => {
    const propToLabelMap = new Map(columnData.value.map(item => [item.prop, item.label]));
    const restructuredTableData = tableData.value.map(row => {
        const newRow = {};
        for (const prop in row) {
            if (row.hasOwnProperty(prop) && propToLabelMap.has(prop)) {
                newRow[propToLabelMap.get(prop)] = row[prop];
            }
        }
        return newRow;
    });
    return restructuredTableData;
};

const exportToExcel = () => {
    const newTableData = resetTableData();
    const worksheet = XLSX.utils.json_to_sheet(newTableData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    const excelBuffer = XLSX.write(workbook, {
        bookType: 'xlsx',
        type: 'array',
    });
    const data = new Blob([excelBuffer], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
    });
    saveAs(data, 'tableData.xlsx');
};
const handle = async () => {
    if (await validate()) {
        let arr = generateRandomNumbers(formData.value)
        tableData.value = arr.map(j => {
            return {
                num: j
            }
        })
        state.csvValue = arr.map(type => `${type}`).join("\n");
        copyValue(state.csvValue)
    }
}
const validate = async () => {
    try {
        await formRef.value.validate()
        return true
    } catch (e) {
        return false
    }
}
defineExpose({ validate })
</script>

<style lang="scss" scoped>
.container {
    height: 100%;
    overflow-y: auto;
    background: #f7f8fa;
    margin: 10px 0;
}

</style>

